package com.lungle.warmdiary.app.view.me.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseActivity;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.response.Tag;
import com.lungle.warmdiary.app.view.me.adapter.TagAdapter;
import com.umeng.analytics.MobclickAgent;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by God on 2016/8/9.
 */
public class SelectTagFragment extends BaseFragment {
    private static final String SELECT_TAG_SCREEN = "select tag screen";

    public static final int CATALOG_INDUSTRY = 1;
    public static final int CATALOG_INTEREST = 2;
    public static final String RESPONSE = "select_result";

    @Bind(R.id.tv_limit_tip)
    TextView mTvLimitTip;
    @Bind(R.id.gv_container)
    GridView mGvContainer;
    private int catalog;

    private List<Tag> mTagList;
    private TagAdapter mAdapter;
    private List<Tag> selectedList = new ArrayList<>();

    private int INDUSTRY_MAX_SELECTED = 1;
    private int INTEREST_MAC_SELECTED = 5;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tag;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(SELECT_TAG_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(SELECT_TAG_SCREEN);
        MobclickAgent.onPause(getActivity());

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        ButterKnife.bind(this, view);
        initData();
        initView(view);
        return view;
    }

    @Override
    public void initView(View view) {
        BaseActivity baseActivity = (BaseActivity) getActivity();
        if (catalog == CATALOG_INDUSTRY) {
            mTvLimitTip.setText(Html.fromHtml("最多选<font color=#FA4848>1</font>行业"));
            baseActivity.setActionBarTitle("行业选择");
        } else {
            mTvLimitTip.setText(Html.fromHtml("最多选<font color=#FA4848>5</font>个标签"));
            baseActivity.setActionBarTitle("标签选择");
        }
    }


    @Override
    public void initData() {
        catalog = getArguments().getInt("catalog");
        if (getArguments().getSerializable("select_tags") != null) {
            selectedList.addAll((Collection<? extends Tag>) getArguments().getSerializable("select_tags"));
        }
        getTag(catalog);
    }


    private void getTag(int catalog) {
        showWaitDialog();
        Observable<Result<List<Tag>>> tags;
        if (catalog == CATALOG_INDUSTRY) {
            tags = ApiFactory.getUserApi().getIndustryList();
        } else {
            tags = ApiFactory.getUserApi().getTagList();
        }
        tags.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<List<Tag>>>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result<List<Tag>> tagResult) {
                        super.onNext(tagResult);
                        mTagList = tagResult.getData();
                        mAdapter = new TagAdapter(getActivity(), mTagList, selectedList, onMultItemClick);
                        mGvContainer.setAdapter(mAdapter);
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable(RESPONSE, (Serializable) selectedList);
        intent.putExtras(bundle);
        if (catalog == CATALOG_INDUSTRY) {
            getActivity().setResult(MediaAddResultFragment.REQUEST_INDUSTRY, intent);
        } else if (catalog == CATALOG_INTEREST) {
            getActivity().setResult(MediaAddResultFragment.REQUEST_INTEREST, intent);
        }

        getActivity().finish();
        return true;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.active_detail, menu);

        menu.findItem(R.id.login_menu_send);
    }


    TagAdapter.onMultiItemSelectListener onMultItemClick = new TagAdapter.onMultiItemSelectListener() {

        @Override
        public void onItemClick(View v, int Position, CheckBox checkBox, TextView textView) {


            if (checkBox.isChecked()) {
                checkBox.setChecked(false);
                textView.setSelected(false);
                for (int i = 0; i < selectedList.size(); i++) {
                    if (textView.getText().toString().equals(selectedList.get(i).getName())) {
                        selectedList.remove(i);
                    }
                }
            } else {
                if (catalog == CATALOG_INDUSTRY && selectedList.size() >= INDUSTRY_MAX_SELECTED) {

//                    AppContext.showToast(String.format("最多选择%s个", INDUSTRY_MAX_SELECTED));
//                    return;
                    selectedList.remove(0);

                } else if (catalog == CATALOG_INTEREST && selectedList.size() >= INTEREST_MAC_SELECTED) {
                    AppContext.showToast(String.format("最多选择%s个", INTEREST_MAC_SELECTED));
                    return;
                }
                checkBox.setChecked(true);
                textView.setSelected(true);
                selectedList.add(mTagList.get(Position));
            }
            mAdapter.notifyDataSetChanged();
        }
    };
}
